package com.windbell.pick;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.windbell.util.PickerUtils;

public abstract class BasePicker {
	public static final String CHARSET_UTF = "UTF-8";
	public static final String CHARSET_GBK = "GBK";
	public static String AURL = "aurl", ATITLE = "atitle", TITLE = "title",
			Body = "body";

	/**
	 * 获取列表
	 * 
	 * @return
	 */
	abstract public List<Map> list();

	/**
	 * 通过单个列表获取文章内容
	 * 
	 * @param map
	 * @return
	 */
	abstract public Map context(Map map);

	/**
	 * 解析A的URL和TITLE
	 * 
	 * @param a
	 * @return
	 */
	public static Map parseA(String a) {
		Map map = new HashMap();
		String url = limit(a, "href=", " ");
		url = url.substring(5, url.length());
		url = url.trim();
		if (!url.startsWith("http")) {
			url = url.substring(1, url.length() - 1);
		}
		String title = limit(a, ">", "<");
		title = title.substring(1, title.length() - 1);
		map.put(AURL, url);
		map.put(ATITLE, title);
		return map;
	}

	public static List<String> limitsByTag(String cStr, String tag) {
		List list = new ArrayList();
		while (true) {
			list.add(limitByTag(cStr, tag));
			cStr = subString(cStr, "</" + tag + ">", cStr.indexOf("<" + tag));
			if (cStr.indexOf("<" + tag) == -1) {
				break;
			}
		}
		return list;
	}

	public static String subString(String cStr, String flag, int index) {
		cStr = cStr.substring(cStr.indexOf(flag, index) + flag.length(),
				cStr.length());
		return cStr;
	}

	public static String limitByTag(String context, String tag) {
		String aStr = limit(context, "<" + tag, "</" + tag + ">");
		return aStr;
	}

	public static String limit(String context, String sStr, String eStr) {
		int start = context.indexOf(sStr);
		PickerUtils.equles_1(start, context, sStr);
		int end = context.indexOf(eStr, start);
		PickerUtils.equles_1(end, context, eStr);
		String listStr = context.substring(start, end + eStr.length());
		return listStr;
	}
}
